import React, { useState, useEffect } from "react";
import { Table, Button, Modal, Tree } from "antd";
import {
  DeleteOutlined,
  UnorderedListOutlined,
  ExclamationCircleOutlined
} from "@ant-design/icons";
import axios from "axios";
const { confirm } = Modal;

export default function RoleList() {
  const [dataSource, setdateSource] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [treeData, settreeData] = useState([]);
  const [treeCheckedKeys, settreeCheckedKeys] = useState([]);
  const [currentId, setcurrentId] = useState([]);
  useEffect(() => {
    axios.get("/roles").then(({ data }) => {
      setdateSource(data);
    });
    axios
      .get("/rights?_embed=children")
      .then(({ data }) => {
        settreeData(data);
      });
  }, []);
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render: id => <b>{id}</b>
    },
    {
      title: "角色列表",
      dataIndex: "roleName"
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            <Button
              danger
              icon={<DeleteOutlined />}
              shape="circle"
              size="large"
              style={{ marginRight: "10px" }}
              onClick={() => showDelConfirm(item)}
            />
            <Button
              type="primary"
              icon={<UnorderedListOutlined />}
              shape="circle"
              size="large"
              onClick={() => showModal(item)}
            />
          </div>
        );
      }
    }
  ];
  function showDelConfirm(item) {
    confirm({
      title: "您确定删除该角色吗?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        const list = dataSource.filter(v => v.id !== item.id);
        setdateSource(list);
        axios.delete(`/roles/${item.id}`);
      },
      onCancel() {}
    });
  }
  const showModal = item => {
    setIsModalVisible(true);
    settreeCheckedKeys(item.rights);
    setcurrentId(item.id);
  };
  const handleOk = () => {
    setIsModalVisible(false);
    const list = dataSource.map(v => {
      if (v.id === currentId) {
        return {
          ...v,
          rights: treeCheckedKeys
        };
      }
      return v;
    });
    setdateSource(list);
    axios.patch(`/roles/${currentId}`, {
      rights: treeCheckedKeys
    });
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const treeOnCheck = data => {
    settreeCheckedKeys(data.checked);
  };
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{ pageSize: 5 }}
        rowKey={row => row.id}
      />
      <Modal
        title="权限配置"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Tree
          checkable
          checkStrictly
          treeData={treeData}
          checkedKeys={treeCheckedKeys}
          onCheck={treeOnCheck}
        />
      </Modal>
    </div>
  );
}
